<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getUniqueCodePrintList"
        uniqueId="mesBoxcodeprintHistoryTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="formDescDialog"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>
    <el-dialog
      width="20%"
      :title="$i18n.t('mesUniqueCodePrintingRecord.print')"
      :visible.sync="innerVisible"
      :append-to-body="true"
      @close="clearFormDialog()"
      v-loading="loding"
      :close-on-click-modal="false"
    >
      <el-form :model="form">
        <el-form-item :label="$i18n.t('mesUniqueCodePrintingRecord.printingTimes')" label-width="85px">
          <el-input
            size="small"
            disabled
            v-model="form.printingTimes"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearFormDialog()">{{
          $t("common.cancel")
        }}</el-button>
        <el-button type="primary" @click="handleRequest">{{
          $t("common.submit")
        }}</el-button>
      </div>
    </el-dialog>

    <repairPrintTable ref="repairPrintTables"></repairPrintTable>
  </div>
</template>

<script>
import {
  operateList,
  searchConfig,
  importFormDescDialog,
  formDescDialog,
  rowConfig,
} from "./config";
import {
  getUniqueCodePrintList,
  uniqueCodePrintRowDetail,
  getPrinttypeList,
  selectListByConfigurationCode,
  getPrintingTimes,
} from "@/api/print/mesProdBarcodePrint";
import { printTemplateInfoName } from "@/api/barcodeprint/mesBarcodeprintHistory";

import uploadNoAuto from "@/components/upload-no-auto";
import { uniqueKey, setPrintData } from "@/utils/judge.js";
import repairPrintTable from "./components/repairPrintTable.vue";
export default {
  name: "mesUniqueCodePrintingRecord",
  components: {
    repairPrintTable,
  },
  data() {
    return {
      innerVisible: false,
      loding: false,
      printRow: [],
      form: { printingTimes: 0 },
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      formDataDialog: {},
      formDescDialog, //新增修改框
      searchConfig,
      operateList,
      getUniqueCodePrintList,
      isLoadingImport: false, // 导入数据loading
      importData: {}, //导入数据
      importVisible: false,
      importFormDescDialog, // 导入字段配置
      // 列表页字段的绑定配置
      column: [
        {
          type: "selection",
          fixed: "left",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          fixed: "left",
          width: 60,
        },

        {
          prop: "barcode",
          label: $i18n.t("mesUniqueCodePrintingRecord.uniqueCode"),
          fixed: "left",
          minWidth: 350,
          showOverflowTooltip: true,
        },
        // {
        //   prop: "count",
        //   label: $i18n.t("mesUniqueCodePrintingRecord.volume"),
        //   fixed: "left"
        // },
        {
          prop: "planCode",
          label: $i18n.t("mesUniqueCodePrintingRecord.planCode"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "orderCode",
          label: $i18n.t("mesUniqueCodePrintingRecord.prodWorkOrderCode"),
          minWidth: 240,
          showOverflowTooltip: true,
        },
        {
          prop: "prodCode",
          label: $i18n.t("mesUniqueCodePrintingRecord.prodCode"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "prodName",
          label: $i18n.t("mesUniqueCodePrintingRecord.prodName"),
          minWidth: 280,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesCode",
          label: $i18n.t("mesUniqueCodePrintingRecord.seriesCode"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "seriesName",
          label: $i18n.t("mesUniqueCodePrintingRecord.seriesName"),
          minWidth: 180,
          showOverflowTooltip: true,
        },

        {
          prop: "barcodePrintTemp",
          label: $i18n.t("mesUniqueCodePrintingRecord.barcodePrintTemp"),
          minWidth: 240,
          showOverflowTooltip: true,
        },
        {
          prop: "printtime",
          label: $i18n.t("mesUniqueCodePrintingRecord.printTime"),
          width: 180,
        },
        {
          prop: "printtype",
          label: $i18n.t("mesUniqueCodePrintingRecord.printType"),
          minWidth: 120,
          optionProp: {
            value: "value",
            label: "description",
          },
          option: async (data) => {
            const list = await getPrinttypeList();
            return list.data.result;
          },
        },
        {
          prop: "userName",
          label: $i18n.t("mesUniqueCodePrintingRecord.printByName"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "createByName",
          label: $i18n.t("common.createByName"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "createTime",
          label: $i18n.t("common.createTime"),
          width: 180,
        },
        {
          prop: "updateByName",
          label: $i18n.t("common.updateByName"),
          minWidth: 180,
          showOverflowTooltip: true,
        },
        {
          prop: "updateTime",
          label: $i18n.t("common.updateTime"),
          width: 180,
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: 120,
          fixed: "right",
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              />
            );
          },
        },
      ],
    };
  },
  computed: {},
  methods: {
    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.disableFields(false);
          this.formDataDialog = {};
          this.visible = true;
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch',{name:$i18n.t('mesUniqueCodePrintingRecord.name')}), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            const ids = data.rows.map((val) => val.id).join(",");
            this.rowDel(ids);
          });
        },
        import: () => {
          this.importDialogData = {};
          this.importVisible = true;
        },
        repairPrint: async () => {
          const workshopList = uniqueKey(data.rows, "workshopCode");
          if (workshopList.length > 1) {
            this.$message.warning(
              $i18n.t("mesUniqueCodePrintingRecord.sameWorkshop")
            );
            return;
          }
          const lineList = uniqueKey(data.rows, "lineCode");
          if (lineList.length > 1) {
            this.$message.warning(
              $i18n.t("mesUniqueCodePrintingRecord.sameLine")
            );
            return;
          }
          const prodList = uniqueKey(data.rows, "prodCode");
          if (prodList.length > 1) {
            this.$message.warning(
              $i18n.t("mesUniqueCodePrintingRecord.sameProd")
            );
            return;
          }
          const { workshopCode, lineCode } = data.rows[0];
          const configData = {
            configurationCode: "com_unique_code_reviewed",
          };
          if (lineCode) {
            configData.levelType = "5";
            configData.lineCode = lineCode;
          } else {
            configData.levelType = "4";
            configData.workshopCode = workshopCode;
          }
          // 查询补打是否需要审核
          this.loading = true;
          const res = await selectListByConfigurationCode(configData);
          const { result } = res.data;
          this.loading = false;
          //  true 需要审核  false 不需要审核
          let bool = false;
          if (result && result.length) {
            if (result[0].value == "1") {
              bool = true;
            }
          }
          // 如果需要审核，跳转补打申请页面
          if (bool) {
            // 如果需要审核，只能选择1个条码
            if (data.rows.length > 1) {
              this.$message.warning(
                $i18n.t("mesUniqueCodePrintingRecord.oneCode")
              );
              return;
            }
            this.$refs.repairPrintTables.init({
              ...data.rows[0],
              isPrint: 0,
            });
          } else {
            this.printRow = data.rows;
            /* // ---------获取打印次数-----------------
            let res = await getPrintingTimes({
              goodsCode: data.rows[0].prodCode
            })
            if (res.data.result && res.data.result.frequency) {
              this.form.printingTimes = res.data.result.frequency
            }
            this.innerVisible = true*/
            this.handleRequest();
          }
        },
      };
      fnc[data.handleName]();
    },
    async handleRequest() {
      const tempList = uniqueKey(this.printRow, "barcodePrintTemp");
      if (tempList.length > 1) {
        this.$message.warning($i18n.t("mesUniqueCodePrintingRecord.limitTemp"));
        return;
      }
      /*  if (this.form.printingTimes == 0) {
        this.$message.warning($i18n.t('printBoxCode.unableToPrint'))
        return
      }*/
      // // const temp = await printTemplateInfoName({
      // //   templateName: tempList[0].barcodePrintTemp
      // // })
      // // const barcodeInfo = {
      // //   ...temp.data.result[0],
      // //   values: this.printRow
      // // }
      // this.innerVisible = false;
      // // ----条码打印多份（条码数量根据打印次数printingTimes重新计算）----
      // let newInfoList = [];
      // barcodeInfo.values.forEach((v) => {
      //   newInfoList = [...newInfoList, ...Array(Number(1)).fill(v)];
      // });
      // barcodeInfo.values = newInfoList;
      this.refresh();
      let { barcodePrintTempCode, barcodePrintTemp } = this.printRow[0];
      setPrintData(
        {
          code: barcodePrintTempCode,
          name: barcodePrintTemp,
          status: 1,
        },
        this.printRow
      );
      this.$router.push("/splitPrint");
    },
    clearFormDialog() {
      this.innerVisible = false;
      this.form.printingTimes = 0;
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name;
      const fnc = {
        edit: () => {
          this.disableFields(false);
          this.rowDetail(row.id);
          this.visible = true;
        },
        detail: () => {
          this.disableFields(true);
          this.rowDetail(row.id);
          this.visible = true;
        },
        // delete: () => {
        //   this.$confirm("此操作将删除该箱码打印历史记录表, 是否继续?", "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning",
        //   }).then(() => {
        //     this.rowDel(row.id);
        //   });
        // },
      };
      fnc[handleName]();
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true;
      api(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || title);
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      const params = this.formDataDialog.id
        ? { title: $i18n.t('common.editSuccess'), api: rowUpdate, data }
        : { title: $i18n.t('common.addSuccess'), api: rowCreate, data };
      this.doSubmit(params);
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          const message = res.data.message;
          this.$message.success(message || $i18n.t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag;
      this.formDescDialog.isShowSubmitBtn = !flag;
    },
    rowDetail(id) {
      uniqueCodePrintRowDetail(id).then((res) => {
        this.formDataDialog = res.data.result;
      });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },
    //数据文件上传
    upLoadHandleChange(file) {
      this.$set(this.importData, "file", file);
    },
    // 提交导入信息
    handleSubmitImport() {
      if (!this.importData.file) {
        this.$message.error($i18n.t("common.uploadMsg"));
        return;
      }
      const formData = new FormData();
      formData.append("file", this.importData.file.get("file"));
      this.isLoadingImport = true;
      importData(formData)
        .then((res) => {
          this.$message.success($i18n.t("common.importSuccess"));
          this.isLoadingImport = false;
          this.importVisible = false;
          this.refresh();
        })
        .catch((error) => {
          console.log("错误", error);
          this.$set(this.importData, "file", null);
        })
        .finally(() => {
          this.isLoadingImport = false;
          this.$refs.uploadNoAuto.clearFiles();
        });
    },
  },
};
</script>
